import BaseTable from "@/components/Table/BaseTable";
import { useCallback, useEffect, useState, useRef } from "react";
import { INIT_PAGINATION } from "@/utils/config";
import type { PagePermission, TableOptions } from "@/types/public";
import { usePublicStore } from "@/stores";
import { useCommonStore } from "@/hooks/useCommonStore";
import { checkPermission } from "@/utils/permissions";
import BaseContent from "@/components/Content/BaseContent";
import { EditTwoTone, DeleteTwoTone } from "@ant-design/icons";
import { type FormInstance, Button, Row, Col, Switch, Select, Input } from "antd";
import { searchList, tableColumns1, tableColumns2 } from "./model.ts";
import BaseSearch from "@/components/Search/BaseSearch";
import BasePagination from "@/components/Pagination/BasePagination";
import BaseCard from "@/components/Card/BaseCard";
import BaseModal from "@/components/Modal/BaseModal";
import { PlusOutlined } from "@ant-design/icons";
import type { BaseFormData } from "@/types/form";
import "./index.less";

// 当前行数据
interface RowData {
    id: string;
}

function Cargo() {
    const isRefreshPage = usePublicStore((state) => state.isRefreshPage);
    const setRefreshPage = usePublicStore((state) => state.setRefreshPage);
    const { permissions } = useCommonStore();

    const [isLoading, setLoading] = useState(false);
    const [isLoading2, setLoading2] = useState(false);
    const [isFetch, setFetch] = useState(false);
    const [page, setPage] = useState(INIT_PAGINATION.page);
    const [pageSize, setPageSize] = useState(INIT_PAGINATION.pageSize);
    const [total, setTotal] = useState(0);
    const [tableData, setTableData] = useState<BaseFormData[]>([]);
    const [searchData, setSearchData] = useState({});
    const [isCreateOpen, setCreateOpen] = useState(false);
    const [createTitle, setCreateTitle] = useState("");
    const [createId, setCreateId] = useState("");
    const [createData, setCreateData] = useState({});
    const [isCreateLoading, setCreateLoading] = useState(false);
    const createFormRef = useRef<FormInstance>(null);
    const [selectedRowKey, setSelectedRowKey] = useState(null);

    // 权限前缀
    const permissionPrefix = "/system";
    const pagePermission: PagePermission = {
        page: checkPermission(`${permissionPrefix}/cargo`, permissions),
    };

    /** 获取表格数据 */
    const getPage = useCallback(async () => {
        const params = { ...searchData, page, pageSize };
        console.log(createId);
        console.log(createData);
        console.log(setCreateLoading(false));
        try {
            setLoading(true);
            console.log(params);
            setTimeout(() => {
                setTableData([
                    { username: "username", id: "11" },
                    { username: "username", id: "222" },
                    { username: "username", id: "333" },
                ]);
                setTotal(1);
            }, 300);
        } finally {
            setFetch(false);
            setLoading(false);
        }
    }, [page, pageSize, searchData]);
    const onSearch = (values: FormData) => {
        setPage(1);
        setSearchData(values);
        setFetch(true);
    };

    // 首次进入自动加载接口数据
    useEffect(() => {
        getPage();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 如果是新增或编辑成功重新加载页面
    useEffect(() => {
        if (isRefreshPage) {
            setRefreshPage(false);
            getPage();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isRefreshPage]);

    useEffect(() => {
        if (isFetch) getPage();
    }, [getPage, isFetch]);

    const onChangePagination = (page: number, pageSize: number) => {
        setPage(page);
        setPageSize(pageSize);
        setFetch(true);
    };

    const optionRender: TableOptions<object> = (_, record) => (
        <>
            {<EditTwoTone style={{ marginLeft: 5 }} onClick={() => onDelete((record as RowData).id)} />}
            {<DeleteTwoTone style={{ marginLeft: 15 }} twoToneColor="#ef0a38" onClick={() => onDelete((record as RowData).id)} />}
        </>
    );

    const onDelete = async (id: string) => {
        try {
            console.log(id);
            setLoading(true);
        } finally {
            setLoading(false);
        }
    };

    const onCreate = () => {
        setCreateOpen(true);
        setCreateTitle("新增订单明细");
        setCreateId("");
        setCreateData({});
    };

    /** 表格提交 */
    const createSubmit = () => {
        createFormRef.current?.submit();
    };

    /** 关闭新增/修改弹窗 */
    const closeCreate = () => {
        setCreateOpen(false);
    };

    const [tableData2, setTableData2] = useState<BaseFormData[]>([]);

    const handleRowClick = (record) => {
        setSelectedRowKey(record.id);
        setLoading2(true);
        setTimeout(() => {
            setTableData2([
                { username: "username", id: "11" },
                { username: "username", id: "222" },
                { username: "username", id: "333" },
            ]);
            setLoading2(false);
        }, 400);
    };

    const rowClassName = (record) => {
        return record.id === selectedRowKey ? "selected-row" : "";
    };

    const leftContentRender = (
        <Button type="primary" className="small-btn" disabled={!selectedRowKey} icon={<PlusOutlined />} onClick={onCreate}>
            新增
        </Button>
    );

    return (
        <>
            <BaseContent isPermission={pagePermission.page}>
                <BaseCard>
                    <BaseSearch list={searchList()} data={searchData} isLoading={isLoading} handleFinish={onSearch} />
                </BaseCard>

                <BaseCard className="mt-10px">
                    <BaseTable
                        isLoading={isLoading}
                        columns={tableColumns1()}
                        dataSource={tableData}
                        getPage={getPage}
                        onRow={(record) => ({
                            onClick: () => handleRowClick(record),
                        })}
                        leftContent={leftContentRender}
                        rowClassName={rowClassName}
                    />
                    <BasePagination disabled={isLoading} current={page} pageSize={pageSize} total={total} onChange={onChangePagination} />
                </BaseCard>

                {selectedRowKey ? (
                    <>
                        <BaseCard className="mt-5px">
                            <h1 style={{ fontSize: 15, color: "#999", fontWeight: "bold", marginBottom: 10 }}>订单明细列表</h1>
                            <BaseTable isLoading={isLoading2} isOperate={false} columns={tableColumns2(optionRender)} dataSource={tableData2} />
                        </BaseCard>
                    </>
                ) : null}

                <BaseModal
                    width={600}
                    title={createTitle}
                    open={isCreateOpen}
                    confirmLoading={isCreateLoading}
                    onOk={createSubmit}
                    onCancel={closeCreate}
                >
                    <>
                        <Row justify="center" style={{ marginBottom: 15 }}>
                            <Col>
                                <Select
                                    placeholder="轨道号"
                                    variant="underlined"
                                    allowClear
                                    style={{ flex: 1, width: 200 }}
                                    options={[
                                        { value: "jack", label: "Jack" },
                                        { value: "lucy", label: "Lucy" },
                                        { value: "Yiminghe", label: "yiminghe" },
                                    ]}
                                />
                            </Col>
                        </Row>
                        <Row style={{ margin: "5px 0 0 0" }}>
                            <Col span={1}></Col>
                            <Col span={6} style={{ fontWeight: "bold", fontSize: 15, paddingLeft: 10 }}>
                                车厢编号
                            </Col>
                            <Col span={6} style={{ fontWeight: "bold", fontSize: 15, paddingLeft: 15 }}>
                                委托重量
                            </Col>
                            <Col span={6} style={{ fontWeight: "bold", fontSize: 15, paddingLeft: 20 }}>
                                车厢自重
                            </Col>
                            <Col span={5} style={{ fontWeight: "bold", fontSize: 15, paddingLeft: 15 }}>
                                是否枪毙
                            </Col>
                        </Row>
                        {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((_item, index) => {
                            return (
                                <>
                                    <Row align="bottom" gutter={20} style={{ marginTop: index !== 0 ? 10 : 0 }}>
                                        <Col span={1}>{index + 1}</Col>
                                        <Col span={6}>
                                            <Input placeholder="" variant="underlined" />
                                        </Col>
                                        <Col span={6}>
                                            <Input placeholder="" variant="underlined" />
                                        </Col>
                                        <Col span={6}>
                                            <Input placeholder="" variant="underlined" />
                                        </Col>
                                        <Col span={5}>
                                            <Switch size="small" />
                                        </Col>
                                    </Row>
                                </>
                            );
                        })}

                        <Row style={{ position: "absolute", bottom: "15px", left: "40px" }}>
                            <Col>
                                <Select
                                    placeholder="选择方向"
                                    variant="underlined"
                                    style={{ flex: 1, width: 200 }}
                                    allowClear
                                    options={[
                                        { value: "jack", label: "Jack" },
                                        { value: "lucy", label: "Lucy" },
                                        { value: "Yiminghe", label: "yiminghe" },
                                    ]}
                                />
                            </Col>
                        </Row>
                    </>
                </BaseModal>
            </BaseContent>
        </>
    );
}

export default Cargo;
